package egovframework.npqs.pqi.mobile.util;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.SimpleTimeZone;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import egovframework.npqs.pqi.mobile.R;

public class BrUtilManager {

	public final String TAG = "BrUtilManager";
	private static BrUtilManager instance = null;
	private boolean mIsBackKeyPressed = false;
	private long mCurrentTimeInMillis = 0;
	private final int BACKEY_TIMEOUT = 2000;
	private final int MSG_TIMER_EXPIRED = 1;
	private boolean isInternet = false;
	
	public synchronized static BrUtilManager getInstance() {
		if (instance == null) {
			synchronized (BrUtilManager.class) {
				if (instance == null) {
					instance = new BrUtilManager();
				}
			}
		}
		return instance;
	}
	
	/**
	 * 토스트 메세지를 띄운다.
	 * @param context
	 * @param msg
	 */
	public void showToast(Context context, String msg) {
		Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
	}
	
	public void StrickModePolicy() {
		int nSDKVersion = Integer.parseInt(Build.VERSION.SDK);
		if (nSDKVersion > 10) // 2.1?�꾨릭
		{
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
	}
	

	/**
	 * string 데이터 인코딩
	 * @param value
	 * @return
	 */
	public  String StringEncoding(String value){
		String encoding = null;
		try {
			 encoding = java.net.URLEncoder.encode(new String(value.getBytes("UTF-8"))); 
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encoding;
	}
	
	/**
	 * 앱 버젼 가져오기
	 * @param context
	 * @return
	 */
	public String GetVersion(Context context) {
		try {
			PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);

			return pinfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 키보드 숨기기
	 * @param context
	 * @param p1
	 */
	public void InputKeybordHidden(Context context , EditText p1){
		final InputMethodManager imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(p1.getWindowToken(), 0);
	}
	
	/**
	 * 키보드 보이기
	 * @param context
	 * @param p1
	 */
	public void InputKeybordShow(Context context , EditText p1){
		final InputMethodManager imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
	}
	
	/**
	 * sdk버전 가져오기
	 * @return
	 */
	public  int mySDK() {
		return Integer.parseInt(Build.VERSION.SDK);
	}
	
	/**
	 * 
	 * @param context
	 * @return
	 */
	public boolean ChkGps(Context context) {
		String gs = android.provider.Settings.Secure.getString(context.getContentResolver(),android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		if (gs.indexOf("gps", 0) < 0 && gs.indexOf("network", 0) < 0) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 휴대폰번호 가져오기
	 * @param context
	 * @return
	 */
	public String getPhoneNumber(Context context) {
		TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String phoneNum = telManager.getLine1Number();
		if (phoneNum != null) {
			if (phoneNum.startsWith("+82")) {
				phoneNum = "0" + phoneNum.substring(3);
			}
		} else
			phoneNum = "";
		return phoneNum;
	}
	
	/**
	 * 종료 EXIT 토스트 띄우기
	 * @param context
	 */
	public void ShowExitToast(Context context) { // exit 토스트
		if (mIsBackKeyPressed == false) {
			mIsBackKeyPressed = true;
			mCurrentTimeInMillis = Calendar.getInstance().getTimeInMillis();
			
			showToast(context,context.getResources().getString(R.string.back_finish));

			startTimer();
		} else {
			mIsBackKeyPressed = false;
			if (Calendar.getInstance().getTimeInMillis() <= (mCurrentTimeInMillis + (BACKEY_TIMEOUT))) {
				((Activity) context).moveTaskToBack(true);

				/*for (int i = 0; i < ActivityMain.mAt.size(); i++) {
					LinnoApplication.mAt.get(i).finish();
				}*/
				android.os.Process.killProcess(android.os.Process.myPid());
			}
		}
	}

	private void startTimer() {
		mTimerHander.sendEmptyMessageDelayed(MSG_TIMER_EXPIRED, BACKEY_TIMEOUT);
	}

	private Handler mTimerHander = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_TIMER_EXPIRED: {
				mIsBackKeyPressed = false;
			}
				break;
			}
		}
	};
	
	/**
	 * 네트워크 상태 체크
	 * @param activity
	 * @return
	 */
	public boolean isInternet(Activity activity) {
		internetState(activity);
		return isInternet();
	}
	
	private boolean isInternet() {
		return isInternet;
	}

	private void internetState(Activity activity) {
		ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		NetworkInfo mobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		NetworkInfo wibro = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);

		if (wifi.isConnected() || mobile.isConnected() || wibro.isConnected()) {
			isInternet = true;
		} else {
			isInternet = false;
		}
	}
	
	public Boolean isNetworkConnected(Context context) {
		ConnectivityManager connectivityManager; 
		connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

		if(networkInfo == null) {
			return false;
		} else if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		} else if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
			return true;
		} else {
			return false;
		}
	}	
	
	/**
	 * 액티비티 notitle 만들기
	 * @param activity
	 */
	public void onActivityNoTitle(Activity activity) {
		activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
	}

	/**
	 *	dialog 띄우기
	 * @param context
	 * @param title
	 * @param msg
	 * @param version
	 */
	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	public void ShowDialog(Context context, String title, String msg,int version) { // 다이얼로그
		AlertDialog.Builder a_builder = null;
		a_builder = new AlertDialog.Builder(context,AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
		a_builder.setTitle(title).setMessage(msg).setCancelable(true)
				.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		a_builder.show();
	}
	
	/**
	 * progress dialog 띄우기
	 * @param mContext
	 * @param msg
	 * @param version
	 * @return
	 */
	public ProgressDialog ShowProgressDialog(Context mContext, String msg,int version) {
		ProgressDialog mdial = null;
		 if (version < 15) {
			mdial = ProgressDialog.show(mContext, null, msg, true, false);
		} else {
			mdial = new ProgressDialog(mContext,ProgressDialog.THEME_HOLO_LIGHT);
			mdial.setMessage(msg);
			mdial.setCancelable(false);
			mdial.setIndeterminate(true);
			mdial.show();
		 }

		return mdial;
	}
	
	/**
	 * 스크린 width
	 * @param context
	 */
	public int getScreenWidth(Context context){
		int mScreenWidth = context.getResources().getDisplayMetrics().widthPixels;
		return mScreenWidth;
	}
	
	/**
	 * 스크린height
	 * @param context
	 */
	public int getScreenHeight(Context context){
		int  mScreenHeight = context.getResources().getDisplayMetrics().heightPixels;
		return mScreenHeight;
	}
	
	public String getStringJSONObject(JSONObject jsonObject, String itemName) {
		try {
			return jsonObject.getString(itemName);
		} catch (JSONException e) {
			e.printStackTrace();
			return "";
		}

	}
	
	public int getIntJSONObject(JSONObject jsonObject, String itemName) {
		try {
			return jsonObject.getInt(itemName);
		} catch (JSONException e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	public static String getMonthAgoDate(int month) {
		Calendar cal = Calendar.getInstance(new SimpleTimeZone(0x1ee6280, "KST"));
		if(month == 3){
			cal.add(Calendar.MONTH ,-3); // 한달전 날짜 가져오기
		}else if(month == 5){
			cal.add(Calendar.MONTH ,-5); // 한달전 날짜 가져오기
		}else if(month == 6){
			cal.add(Calendar.MONTH ,-6); // 한달전 날짜 가져오기
		}
		java.util.Date monthago = cal.getTime();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
		return formatter.format(monthago);
	}
	
	public static String getCurrentDateTime(int days) {
		//현재 날짜 가져오기 시간 분 까지 가능 
		long chStart = 0;  
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.KOREA);
		Date date = new Date();
		String result = sdf.format(date);
		DateFormat df = new SimpleDateFormat("yyyyMMdd");
	    
	    if(result != ""){
	    	result = result.replaceAll("-","");         //사이사이의 -를 없애고 다 붙인다
	      try {
	        chStart = df.parse(result).getTime();           //스트링형 date를 long형의 함수로 컨버트하고
	        if(days == 1){
	        	chStart -= 1*24*60*60*1000;    //24*60*60*1000 하루치의 숫자를 빼준다
	        }else if(days == 3){
	        	chStart -= 3*24*60*60*1000;    //24*60*60*1000 3일치의 숫자를 빼준다
	        }else if(days == 7){
	        	chStart -= 7*24*60*60*1000;    //24*60*60*1000 7일치의 숫자를 빼준다
	        }
  
	        Date aa = new Date(chStart);         //이것을 다시 날짜형태로 바꿔주고
            result = sdf.format(aa);              //바꿔준 날짜를 yyyyMMdd형으로 바꾼후
	      } catch (ParseException e) {
	        e.printStackTrace();
	      }
	    }

		return result;
	}
	
	public int getPixelToDp(Context context, int pixel) {
		float dp = 0;
		try {
			DisplayMetrics metrics = context.getResources().getDisplayMetrics();
			dp = pixel / (metrics.densityDpi / 160f);
		} catch (Exception e) {
			
		}
		return (int) dp;
	}

	public int getDpToPixel(Context context, int DP) {
		float px = 0;
		try {
			px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DP, context.getResources().getDisplayMetrics());
		} catch (Exception e) {
			
		}
		return (int) px;
	}

	public int getDpToPixel(Context context, float DP) {
		float px = 0;
		try {
			px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DP, context.getResources().getDisplayMetrics());
		} catch (Exception e) {
			
		}
		return (int) px;
	}
	
	public static String isNullCheck(String str){
		String nullStr = "";
		if(str.equals("null")){
			nullStr = "";
		}else{
			nullStr = str;
		}
		
		return nullStr;
	}
	
	public static String isNullCheck2(String str){
		String nullStr = "";
		if(null==str){
			nullStr = "";
		}else{
			nullStr = str;
		}
		
		return nullStr;
	}
	
	public boolean dateCheck(String sDate, String eDate){
		boolean result = false;
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date day1 = null;
			Date day2 = null;
			
			try {
				day1 = format.parse(sDate);
				day2 = format.parse(sDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			int compare = day1.compareTo(day2);
			if (compare > 0){
				result = false;
			}else if (compare <= 0){
				result = true;
			}
		return result;
	}
}
